/**
 *@description 行情信息接收websock接口
 * */
import store from '../store'
import mqtt from 'mqtt'
var client
const options = {
  connectTimeout: 40000,
  clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
  username: "serverclient",
  password: "serverpass",
  clean: true
}

// 初始化websock
function initWebSocket(url = '') {

  client = mqtt.connect(`wss://${window.net}:8083/mqtt`, options)
  client.on('connect', (e) => {
    console.log('连接成功:')
    wsOnOpen()
    client.subscribe('hangqing/+', {qos: 2}, (error) => {
      if (!error) {
        console.log('订阅成功')
      } else {
        console.log('订阅失败')
      }
    })
  })
  // 接收消息处理
  client.on('message', (topic, message) => {
    wsOnMessage(message.toString())
  })
  // 断开发起重连
  client.on('reconnect', (error) => {
    console.log('正在2重连:', error)
  })
  // 链接异常处理
  client.on('error', (error) => {
    console.log('连接2失败:', error)
  })
}

// websock连接成
function wsOnOpen(e) {
  // 连接成功，在store中标记连接状态
  console.log(e)
}

// 接收后台返回的信息
function wsOnMessage({ data }) {
  // 接收消息，体现在store中
  let dataArr = data.split(';')
  // 接收服务端推送的行情
  if(dataArr[0] === '2') {
    store.dispatch('product/processingMarket', dataArr)
  }
  // console.log('----行情信息----')
  // console.log(dataArr)
  // console.log('----行情信息----')
}

function wsClose() {
  client.end()
}

export {
  wsClose,
  initWebSocket,
  wsOnMessage
}
